﻿using System.Reflection;
using System.Linq;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class IServiceCollectionExtensions
    {
        public static IServiceCollection AddInjectionServices<T>(this IServiceCollection services)
        {
            var serviceTypes = GetInjectionServiceTypeList(typeof(T).Assembly);
            foreach (var item in serviceTypes)
            {
                var injection = item.GetCustomAttribute<InjectionAttribute>();
                if (injection!.ServiceType == null)
                {
                    services.Add(new ServiceDescriptor(item, item, injection.Lifetime));
                }
                else
                {
                    services.Add(new ServiceDescriptor(injection!.ServiceType, item, injection.Lifetime));
                }
            }
            return services;
        }

        private static IEnumerable<Type> GetInjectionServiceTypeList(Assembly assembly)
        {
            var serviceType = assembly.GetTypes()
                .Where(a => a.IsClass)
                .Where(a => a.GetCustomAttribute<InjectionAttribute>() != null)
                .Where(a => !a.IsAbstract);
            return serviceType;
        }
    }
}